import { createContext, PropsWithChildren, useState } from "react";
import { fileName2Language} from './utils/index'
import {initFiles} from './files'
export interface File {
    name:string
    value:string
    language:string
}
export interface Files {
    [key:string]:File
}
export interface PlaygroundContextType{
    files:Files
    selectdFileName:string
    setSelectdFileName:(name:string)=>void
    setFiles:(files:Files)=>void
    addFile:(name:string)=>void
    removeFile:(name:string)=>void
    updateFileName:(oldName:string,newName:string)=>void
}
export  const PlaygroundContext = createContext<PlaygroundContextType>({selectdFileName:'App.tsx'} as PlaygroundContextType)

export const PlaygroundProvider = (props:PropsWithChildren)=>{
    const {children} = props
    const [files,setFiles] = useState<Files>(initFiles)
    const [selectdFileName,setSelectdFileName] = useState<string>('main.tsx')
    const addFile = (name:string)=>{
        files[name] = {
            name,
            language:fileName2Language(name),
            value:''
        }
        setFiles({...files})
    }
    const removeFile = (name:string)=>{
        delete files[name]
        setFiles({...files})
    }
    const updateFileName = (oldFieldName: string, newFieldName: string) => {
        if (!files[oldFieldName] || newFieldName === undefined || newFieldName === null) return
        const { [oldFieldName]: value, ...rest } = files
        const newFile = {
          [newFieldName]: {
            ...value,
            language: fileName2Language(newFieldName),
            name: newFieldName,
          },
        }
        setFiles({
          ...rest,
          ...newFile,
        })
      }
      return <PlaygroundContext.Provider value={{files,selectdFileName,setSelectdFileName,setFiles,addFile,removeFile,updateFileName}}>{children}</PlaygroundContext.Provider>
}